package com.ng.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionsUtils {

	public static Set<String> transletPerms(List<String> perms) {
		
		Set<String> set = new HashSet<>();
		
		for(String p : perms) {
			if(p == null || p.isEmpty()) continue;
			
			String[] ps = p.split(",");
			for(String s : ps) {
				set.add(s);
			}
		}
		
		return set ;
		
	}
	
	public static <T> Set<String> transletPerms(List<T> perms ,   TValue<T> tv) {
		
		Set<String> set = new HashSet<>();
		
		for(T p : perms) {
			if(p == null ) continue;
			Object v = tv.getValue(p);
			if(v == null || v.equals("")) continue ;
			
			String[] ps = v.toString().split(",");
			for(String s : ps) {
				set.add(s);
			}
		}
		
		return set ;
		
	}
	
	
	public static String collectionsToString(Collection<String> colls) {
		
		StringBuffer sb = new StringBuffer();
		for(String s : colls) {
			sb.append(s + ",");
		}
		
		if(sb.length() > 1) {
			sb.deleteCharAt(sb.length() - 1 ) ;
		}
		
		return sb.toString();
	}
	
	/**
	 * 列表转树
	 * @param oldList 列表数据
	 * @param translate 转换适配器
	 * @return
	 */
	 public static <T> List<T> list2tree(List<T> oldList , ListTreeTranslate<T> translate) {
		 Map<String,T> newMap = new HashMap<>();
	        List<T> newList = new ArrayList<>();
	        for (T tree : oldList){
	            newMap.put(translate.getKey(tree),tree);
	        }
	        for (T tree : oldList){
	            T parent =   newMap.get(translate.getParentId(tree));
	            if (parent != null){
	                if (translate.getChildrens(parent) == null){
	                    List<T> ch = new ArrayList<>();
	                    ch.add(tree);
	                    translate.setChildrens(ch,parent);
	                }else {
	                    List<T> ch = translate.getChildrens(parent);
	                    ch.add(tree);
	                    translate.setChildrens(ch,parent);
	                }
	            }else {
	                newList.add(tree);
	            }
	        }
	        return newList; 
	 }
	 
	 public interface ListTreeTranslate<T> {
		 /**
		  * 获取节点唯一标识方法
		  * @param node
		  * @return
		  */
		 String getKey(T node);

		 /**
		  * 获取节点父节点唯一标识方法
		  * @param node
		  * @return
		  */
		String getParentId(T node);

		 /**
		  * 子节点
		  * @param node
		  * @return
		  */
		 List<T> getChildrens(T node);

		 /**
		  * 填充child
		  * @param nodes
		  * @param node
		  */
		 void setChildrens(List<T> nodes,T node); 
	 }
	 
}
